<?php
sleep(1);
defined('IN_PHPCMS') or exit('No permission resources.');
$db_book = pc_base::load_model('book_model');
$db_member = pc_base::load_model('member_model');
$db_bookbuy = pc_base::load_model('bookbuy_records_model');
$spend = pc_base::load_app_class('spend','pay',0);

$id = isset($_GET['id'])?intval($_GET['id']):0;
//判断是否登录
$phpcms_auth = param::get_cookie('auth');
$userid = param::get_cookie('_userid');
$username = param::get_cookie('_username');

if($phpcms_auth)
{
    get_book($id);
}
else
{
    echo '{"logined":"-1"}';
}


/**
 * 获指定图书价格信息
 * @param int $id
 * @param $userid
 */
function get_book($id=0)
{
    global $db_bookbuy,$db_member,$userid,$username;

    $query = 'SELECT p.id,p.title,d.price FROM `'.$db_bookbuy->db_tablepre.'book` p INNER JOIN `'.$db_bookbuy->db_tablepre.'book_data` d ON p.id = d.id WHERE p.id = '.$id.'  LIMIT 0,1';

    $res = $db_bookbuy->query($query);
    $row = $db_bookbuy->fetch_array();
	$count = count($row);

    if($count>0)
    {
        if(!ordered_book($id))
        {
            $data = array();
            $data['book_id'] = $id;
            $data['user_id'] = $userid;
            $rows = $db_member->get_one('userid='.$userid,'amount');
            if($rows['amount']<$row[0]['price'])
            {
                echo '{"price":"-2"}'; //余额不足返回-2
            }
            else
            {
                $insert_id = $db_bookbuy->insert($data,true);
                if($insert_id)
                {
                    $price = $row[0]['price'];
                    $book = $row[0]['title'];
                    $flag = spend::amount($price,$book,$userid,$username);
                    if($flag)
                    {
                        echo '{"price":"'.$row[0]['price'].'"}';
                    }

                }
            }
        }
        else
        {
            $where = array('book_id'=>$id,'user_id'=>$userid);
            $res = $db_bookbuy->get_one($where);
            if($res)
            {
                echo '{"price":"-1"}'; //图书已经预定过返回-1
            }
        }

    }

}

/**
 * 判断图书是否预订过
 * @param $id
 * @return bool
 */
function ordered_book($id)
{
    global $db_bookbuy,$userid;

    $userid = param::get_cookie('_userid');
    $query = 'SELECT * FROM `'.$db_bookbuy->db_tablepre.'bookbuy_records` WHERE book_id = '.$id.' AND user_id = '.$userid;
    $db_bookbuy->query($query);
    $row = $db_bookbuy->fetch_array();
    $count = count($row);
    if($count>0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>